{% extends "base.html" %}
{% load i18n %}
{% block head %}
    <title>{% trans "游戏业务管理" %}</title>
    {{ block.super }}
    <style>
        .operator {
            float: right;
        }

        .operator-btn {
            padding: 0 2px;
            height: 20px;
            float: right;
            margin: 6px 5px 0 0;
            display: none;
        }

        .td-bg {
            color: #f0f0f0;
            width: 300px;
            background-color: #d1d0d0;
            font-weight: bold;
        }
        .analysis-label {
            width: 8px;
            height:21px;
            background-color: #3C96FF;
            margin-right: 10px;
            margin-bottom: 10px;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="page-contactus">
        <div style="width: 250px; float: left;margin: 0 10px; height: 500px">
            <div style=" margin: 10px 0 0 20px">
                <span style="font-weight: bold;">选择业务</span>
                <div style="width: 200px">
                    <select id="search_biz_inst_topo" class="bk-form-select" onchange="onBizChange()">
                    </select>
                </div>
            </div>

            <div style=" margin: 10px 0 10px 20px">
                <span style="font-weight: bold;">选择拓扑</span>
            </div>
            <div class="bk-tree" id="bk-tree">
                <ul class="tree-content" id="bk-ul-tops">
                </ul>
            </div>
        </div>

        <div class="bk-tab2 bk-tab2-small" style="margin-left: 280px" id="bk-tab2">
            <div class="bk-tab2-head">
                <ul class="bk-tab2-nav">
                    <li class="tab2-nav-item active">主机列表</li>
                    <li class="tab2-nav-item">业务信息</li>
                    <li class="tab2-nav-item" id="monitor-info">告警信息</li>
                    <li class="tab2-nav-item" id="monitor-analysis">告警分析</li>
                    <li class="tab2-nav-item" id="operational-analysis-1">运营分析(iFrame)</li>
                    <li class="tab2-nav-item" id="operational-analysis-2">运营分析(JS-SDK)</li>
                </ul>
            </div>
            <div class="bk-tab2-content">
                <!-- 主机列表 -->
                <div class="bk-tab2-pane p15 active">
                    <div class="f12">
                        <div style="min-width: 80%">
                            <div style="display: none">
                                配置平台资源信息
                                <span class="bk-tag">主机：</span>
                                <span class="bk-tag bk-gray">业务：</span>
                                <span class="bk-tag bk-light-gray">业务集：</span>
                                <button class="bk-tag bk-primary">交换机：</button>
                                <span class="bk-tag bk-danger">路由器：</span>
                                <span class="bk-tag bk-success">负载均衡：</span>
                                <span class="bk-tag bk-warning">防火墙：</span>
                            </div>
                            <div class="bk-panel-header" style="display: none">
                                <div class="bk-form bk-inline-form">
                                    <div class="bk-form-item">
                                        <label class="bk-label">业务：</label>
                                        <div class="bk-form-content">
                                            <select name="" id="search_biz_infos" class="bk-form-select"
                                                    onchange="search_biz_infos()" style="width: 250px">
                                                {% for biz in bizs %}
                                                    <option value="{{ biz.bk_biz_id }}">
                                                        [{{ biz.bk_biz_id }}]&nbsp;{{ biz.bk_biz_name }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="bk-collapse-panel">
                                <div class="panel-header" role="tab">
                                    <a data-toggle="collapse" class="panel-icon panel-spread"></a>
                                    <h3 data-toggle="collapse" class="panel-title" aria-expanded="true">主机列表</h3>
                                </div>
                                <div id="panel-content2" class="panel-body panel-collapse p0 collapse in"
                                     aria-expanded="true" style="width: 100%">
                                     <div class="king-notice2 king-notice-success notice-borders" id="alert-message"
                                         style="display: none; float: right;">
                                        <i class="fa fa-check-circle"></i>
                                        <div class="notice-text">
                                            <p>故障机切换执行成功</p>
                                        </div>
                                    </div>
                                    <!-- 表格 -->
                                    <table id="hosts" class="bk-table bk-table-header-bordered">
                                        <thead>
                                        <tr>
                                            <th>序号</th>
                                            <th>主机ID</th>
                                            <th>云区域ID</th>
                                            <th>内网IP</th>
                                            <th>主机名</th>
                                            <th>OS类型</th>
                                            <th>MAC地址</th>
                                            <th>操作</th>
                                        </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 业务信息 -->
                <div class="bk-tab2-pane p15">
                    <div class="bk-collapse-panel">
                        <div class="panel-header" role="tab">
                            <a data-toggle="collapse" class="panel-icon panel-spread"></a>
                            <h3 data-toggle="collapse" class="panel-title" aria-expanded="true">基础信息</h3>
                        </div>
                        <div id="node-information1"></div>
                    </div>

                    <div class="bk-collapse-panel">
                        <div class="panel-header" role="tab">
                            <a data-toggle="collapse" class="panel-icon panel-spread"></a>
                            <h3 data-toggle="collapse" class="panel-title" aria-expanded="true">角色</h3>
                        </div>
                        <div id="node-information2"></div>
                    </div>
                </div>
                <!-- 告警信息-->
                <div class="bk-tab2-pane p15">
                    <div id="filter-menu" style=" width: 100%; height:50px;">
                    <select id="alert-status" name="validation_select" class="bk-form-select" style="width: 150px; height: 30px; margin-left: 20px; margin-top: 10px">
                        <option value="">请选择告警状态</option>
                        <option value="ABNORMAL">未恢复</option>
                        <option value="RECOVERED">已恢复</option>
                        <option value="CLOSED">已关闭</option>
                    </select>
                    <select id="alert-shielded" name="validation_select" class="bk-form-select" style="width: 150px; height: 30px; margin-left: 20px; margin-top: 10px">
                        <option value="">请选择是否屏蔽</option>
                        <option value="false">未屏蔽</option>
                        <option value="true">已屏蔽</option>
                    </select>
                    <select id="alert-level" name="validation_select" class="bk-form-select" style="width: 150px; height: 30px; margin-left: 20px; margin-top: 10px">
                        <option value="">请选择告警级别</option>
                        <option value="1">致命</option>
                        <option value="2">预警</option>
                        <option value="3">提醒</option>
                    </select>

                    <input id="alert-ip" type="text" class="bk-form-input" placeholder="请输入过滤IP" style="width:150px; height:30px; margin-left:20px; margin-top: 10px">

                    <button id="search-button" class="bk-button bk-primary bk-button-small" title="开始搜索" style="margin-left:20px; margin-top: 10px; display: inline"><i class="bk-icon icon-search"></i> 开始搜索</button>

                    <div id="display-table-column" class="bk-dropdown-menu" style="position: absolute; margin-left: 30px; margin-top: 10px">
                        <button class="bk-button bk-primary is-icon bk-dropdown-trigger" style="height:32px; line-height:32px;">
                            <i class="bk-icon icon-cog-shape"></i> 显示列
                        </button>
                        <div class="bk-dropdown-content left-align" style="top: 39px;">
                            <ul class="bk-dropdown-list" style="max-height: 400px" id="check-list">
                            </ul>
                        </div>
                    </div>

                </div>
                    <table class="bk-table" id="warning-list">
                        <thead>
                        <tr>
                            <th>告警ID</th>
                            <th style="width: 190px">告警名称</th>
                            <th>告警级别</th>
                            <th>目标IP</th>
                            <th>分类名称</th>
                            <th>状态</th>
                            <th>是否屏蔽</th>
                            <th>是否处理</th>
                            <th>是否确认</th>
                            <th>确认人</th>
                            <th style="width: 190px">策略名称</th>
                            <th>业务名称</th>
                        </tr>
                        </thead>
                        <tbody id="alert-data">
                        </tbody>
                    </table>
                    <div class="bk-table-pagination-wrapper">
                    <div class="bk-table-pagination bk-page bk-page-align-right bk-page-small">
                        <div class="bk-page-list-wrapper" style="float: right; margin-right: 40px">
                            <ul class="bk-page-list" id="tablePaging"></ul>
                        </div>
                    </div>
                </div>
                </div>
                <!-- 告警分析 -->
                <div class="bk-tab2-pane p15">
                    <div style="display: flex;">
                        <label class="analysis-label"></label> 告警名称分布
                        <label class="analysis-label" style="margin-left: 47.2%"></label> 告警IP分布
                    </div>

                    <div style="display: flex;">
                        <div class="bk-collapse-panel" style="width: 50%">
                            <div id="alert_name" style="width:550px; height: 300px;"></div>
                        </div>
                        <div class="bk-collapse-panel" style="width: 50%; margin-left: 100px">
                            <div id="alert_ip" style="width:550px;  height: 300px;"></div>
                        </div>
                    </div>

                    <div style="display: flex; margin-top: 10px">
                        <label class="analysis-label"></label> 告警等级分布
                        <label class="analysis-label" style="margin-left: 47.2%"></label> 告警状态分布
                    </div>
                    <div style="display: flex">
                        <div class="bk-collapse-panel" style="width: 50%">
                            <div id="alert_level" style="width: 550px; height: 300px;"></div>
                        </div>
                        <div class="bk-collapse-panel" style="width: 50%; margin-left: 100px">
                            <div id="alert_status" style="width: 550px; height: 300px;"></div>
                        </div>
                    </div>
                </div>
                <!--运营分析iFrame-->
                <div class="bk-tab2-pane p15" style="height: 1000px;">
                    <iframe
                     src="https://apps.ce.bktencent.com/bk-vision/embed/?uid=c6T4yToKyPWFa899Le8Lp4&bk_app_id=&bk_app_list=['cherrriii']&name=&show_copyright=True&watermark=True&time_readonly=False&show_time=True&show_refresh=True&start_time=now/d&end_time=now/d&preview=False&hide_toolbox=False&hide_filter=False&panels=&refresh=False"
                     style="height: 100%;width: 100%;border: 1px solid rgb(220, 222, 229);">
                    </iframe>
                </div>
                <!--运营分析JS-SDK-->
                <div class="bk-tab2-pane p15" style="height: 1000px;">
                    <link rel="stylesheet" href="https://staticfile.qq.com/bkvision/p8e3a7f52d95c45d795cb6f90955f2800/latest/main.css"/>
                    <div id='bkVision' style='width: 100%;min-height: 1000px;'></div>
                </div>

            </div>
        </div>
    </div>
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" id="modal-button"
        style="display: none">
    </button>
    <div class="modal fade in" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="false">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">故障机切换</h4>
                </div>
                <div class="modal-body">
                    <div>
                        <span>故障机IP:</span>
                        <span id="render-origin-ip" style="margin-left:87px">2</span>
                    </div>
                    <div id="select-template">
                    </div>
                    <div id="select-target-ip">
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="submit-button">提交更改</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
{% endblock %}

{% block extra_block %}
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/daterangepicker-2.0.5/moment.min.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/daterangepicker-2.0.5/daterangepicker.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/umeditor-1.2.2/umeditor.config.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/umeditor-1.2.2/umeditor.min.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/umeditor-1.2.2/lang/zh-cn/zh-cn.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/select2-3.5.2/select2.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/bkSwitcher-1.0/js/bkSwitcher.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/validate-1.14.0/js/jquery.validate.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/bkDropdownMenu-1.0/js/bkDropdownMenu.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/bkTab-1.0/js/bkTab.js"></script>
    <script src="https://staticfile.qq.com/bkvision/p8e3a7f52d95c45d795cb6f90955f2800/latest/chunk-vendors.js"></script>
    <script src="https://staticfile.qq.com/bkvision/p8e3a7f52d95c45d795cb6f90955f2800/latest/chunk-bk-magic-vue.js"></script>
    <script src="https://staticfile.qq.com/bkvision/p8e3a7f52d95c45d795cb6f90955f2800/latest/main.js"></script>
    <script>
      window.BkVisionSDK.init(
          '#bkVision',
        '3ze8kpBYm7BCYLPAL6teBm',
        {
          waterMark:{content: 'bk-vision',} , // 谁赢设置
          apiPrefix: './bkvision/',
          // 下面配置将覆盖分享设置数据
          filters: {},// 设置筛选变量默认值
          show_refresh:true, // 是否展示刷新按钮
          show_time:true, // 是否显示时间过滤器
          time_readonly:false, //时间过滤器是否制度
          start_time: 'now/d', // 时间选择器开始时间
          end_time: 'now/d', // 时间选择器结束时间
        });
    </script>
    <script>
        var tabIndex = 0;
        // 页内选项卡初始化
        $('.bk-tab2').bkTab({
            tabTriggers: '.tab2-nav-item',
            tabPanels: '.bk-tab2-pane',
            onTabChange: function (index, tab) {
                tabIndex = index;
                if (index === 2) {
                    render_alert_table()
                } else if (index === 3) {
                    render_alert_chart()
                } else {
                }

            }
        });

        // 拓扑导航栏
        $('.bk-tree').on('click', 'a', function (event) {
            $('.module').removeClass('open');
            if ($(this).parent('li').hasClass('module')) {
                var bk_module_id = $(this).parent('li').attr("module_id");

            } else if ($(this).parent('li').hasClass('set')) {
                $('.set').removeClass('open');
                var bk_set_id = $(this).parent('li').attr("set_id");
            } else {
                $('.set').removeClass('open');
            }
            $(this).parent('li').toggleClass('open');
            businessInfo.ajax.reload()
        });

        $("#bk-ul-tops").hover(function () {
                $(".operator-btn").show();
            },
            function () {
                $(".operator-btn").hide();
            }
        )

        $('#display-table-column').bkDropdown({
            align: 'left'
        });

        var language = {
            search: "{% trans '搜索：' %}",
            lengthMenu: "{% trans '每页显示 _MENU_ 记录' %}",
            zeroRecords: "{% trans '没找到相应的数据！' %}",
            info: "{% trans '分页 _PAGE_ / _PAGES_ 共 _TOTAL_ 条' %}",
            infoEmpty: "{% trans '暂无数据！' %}",
            infoFiltered: "{% trans '(从 _MAX_ 条数据中搜索)' %}",
            paginate: {
                previous: "{% trans '上一页' %}",
                next: "{% trans '下一页' %}",
            }
        }
    </script>
    <script>
        var bk_biz_id;
        var biz_modules = [];
        var bizNameMapping = {}
        const os_type = JSON.parse('{{ os_type | safe }}')

        // 业务列表查询
        $.ajax({
            url: "{{ SITE_URL }}search_business/",
            method: 'post',
            success: function (data) {
                var biz_topo = "";
                data.data.info.forEach(biz => {
                    biz_topo += '<option value=' + biz.bk_biz_id + '>[' + biz.bk_biz_id + '] ' + biz.bk_biz_name + '</option>';
                    sessionStorage.setItem(biz.bk_biz_id, JSON.stringify({
                        "bk_biz_name": biz.bk_biz_name,
                        "time_zone": biz.time_zone,
                        "language": biz.language,
                        "life_cycle": biz.life_cycle,
                        "create_time": biz.create_time,
                        "bk_biz_maintainer": biz.bk_biz_maintainer,
                        "bk_biz_developer": biz.bk_biz_developer,
                        "bk_biz_productor": biz.bk_biz_productor,
                        "bk_biz_tester": biz.bk_biz_tester,
                        "operator": biz.operator
                    }));
                    bizNameMapping[biz.bk_biz_id] = biz.bk_biz_name
                })
                document.getElementById("search_biz_inst_topo").innerHTML = biz_topo;
                onBizChange();
            }
        });

        // 业务变化时重载页面
        function onBizChange() {
            bk_biz_id = parseInt($("#search_biz_inst_topo option:selected").val());
            // 重新渲染业务信息
            node_infomation();
            // 重新查询业务拓扑
            search_biz_inst_topo();
            // 重新查询主机信息
            businessInfo.ajax.reload()
        }

        // 业务主机资源
        var businessInfo = $("#hosts").DataTable({
            sProcessing: '<img alt="loadding" src="https://magicbox.bk.tencent.com/static_api/v3/components/loading1/images/loading_2_36x36.gif">',//这里很重要，如果你的加载中是文字，则直接写上文字即可，如果是gif的图片，使用img标签就可以加载
            pagingType: "simple_numbers",
            paging: true, //隐藏分页
            pageLength: 10, //每页显示几条数据
            language: language, //汉化
            serverSide: true,
            searchDelay: 500,
            deferLoading: 0,
            ajax: {
                url: '{{ SITE_URL }}list_biz_hosts/',
                method: "post",
                dataType: 'json',
                data: function (d) {
                    return JSON.stringify({
                        "bk_biz_id": bk_biz_id,
                        "bk_set_id": $(".set.open").attr("set_id"),
                        "bk_module_id": $(".module.open").attr("module_id"),
                        "start": d.start,
                        "length": d.length,
                        "search": d.search.value
                    });
                },
            },
            columns: [
                {
                    width: 40,
                    tatgets: 0,
                    data: null,
                    render: function (data, type, row, meta) {
                        return meta.row + 1;
                    }
                },
                {
                    width: 40,
                    tatgets: 1,
                    data: "bk_host_id",
                },
                {
                    width: 40,
                    tatgets: 2,
                    data: "bk_cloud_id",
                },
                {
                    width: 80,
                    tatgets: 3,
                    data: "bk_host_innerip",
                },
                {
                    width: 80,
                    tatgets: 4,
                    data: "bk_host_name",
                },
                {
                    width: 50,
                    tatgets: 5,
                    data: "bk_os_type",
                    render: function (data, type, row, meta) {
                        return null != data ? "<span class=\"bk-tag is-fill bk-success\">" + os_type[data] + "</span>" : "<span class=\"bk-tag is-fill bk-danger\">未知</span>";
                    }
                },
                {
                    width: 80,
                    tatgets: 6,
                    data: "bk_mac",
                },
                {
                    width: 120,
                    tatgets: 7,
                    data: "bk_host_id",
                    render: function (data, type, row, table) {
                        var origin_ip = row.bk_host_innerip.toString()
                        var host_id = row.bk_host_id.toString()
                        var index = table.row
                        // 查询操作日志，host_id=host_id, if status == RUNNING 按钮禁用，否则非禁用
                        var status = get_sops_task_status(host_id)
                        var operate_html = ''
                        if (status == "RUNNING" || status == "PENDING") {
                            operate_html = '<a class="bk-text-button bk-info" onclick="clone_host_property(this)">克隆属性</a><a class="bk-text-button bk-info" onclick="transfer_host_module(' + data + ')">转移模块</a><a class="bk-text-button bk-info" target="_blank" title="查看详情" href="get_host_base_info/?bk_host_id=' +
                            data + '">查看详情</a><a class="bk-text-button bk-info" style="pointer-events:none; color: rgb(185 181 175);" onclick="translation_machine(`' + origin_ip + '`,' + index + ',' + host_id + ')">切换故障机</a>'
                        } else {
                            operate_html = '<a class="bk-text-button bk-info" onclick="clone_host_property(this)">克隆属性</a><a class="bk-text-button bk-info" onclick="transfer_host_module(' + data + ')">转移模块</a><a class="bk-text-button bk-info" target="_blank" title="查看详情" href="get_host_base_info/?bk_host_id=' +
                            data + '">查看详情</a><a class="bk-text-button bk-info" style="color: #88c3ff;" onclick="translation_machine(`' + origin_ip + '`,' + index + ',' + host_id + ')">切换故障机</a>'
                        }
                        return operate_html;
                    }
                }
            ],
        });

        // 业务信息，不做强要求
        function node_infomation() {
            var bk_biz_id = $('#search_biz_inst_topo option:selected').val();
            var nodeinfo = JSON.parse(sessionStorage.getItem(bk_biz_id));

            document.getElementById('node-information1').innerHTML = '<table class="bk-table has-table-striped"> <tbody> ' +
                '<tr> <td class="td-bg">ID</td> <td style="width: 22%">' + bk_biz_id + '</td> <td class="td-bg">业务名</td> <td>' + nodeinfo.bk_biz_name + '</td> </tr> ' +
                '<tr> <td class="td-bg">时区</td> <td style="width: 22%">' + nodeinfo.time_zone + '</td> <td class="td-bg">语言</td> <td>' + nodeinfo.language + '</td> </tr> ' +
                '<tr> <td class="td-bg">生命周期</td> <td style="width: 22%">' + nodeinfo.life_cycle + '</td> <td class="td-bg">创建时间</td> <td>' + nodeinfo.create_time + '</td> </tr> </tbody> </table>';
            document.getElementById('node-information2').innerHTML = '<table class="bk-table has-table-striped"> <tbody> ' +
                '<tr> <td class="td-bg">运维人员</td> <td style="width: 22%">' + nodeinfo.bk_biz_maintainer + '</td> <td class="td-bg">开发人员</td> <td>' + nodeinfo.bk_biz_developer + '</td> </tr> ' +
                '<tr> <td class="td-bg">产品人员</td> <td style="width: 22%">' + nodeinfo.bk_biz_productor + '</td> <td class="td-bg">测试人员</td> <td>' + nodeinfo.bk_biz_tester + '</td> </tr> ' +
                '<tr> <td class="td-bg">操作人员</td> <td style="width: 22%">' + nodeinfo.operator + '</td></tr> </tbody> </table>'
        }

        // 克隆主机属性
        function clone_host_property(event) {
            var src_ip = event.parentNode.parentNode.childNodes[3].textContent
            var dialog = new bkDialog({
                type: 'dialog',
                width: 400,
                padding: 20,
                content: '<label >克隆属性至主机:</label><input class="bk-form-input" style="width: 100%;" id="to_host" placeholder="请输入要克隆的主机...">',
                hasHeader: false,
                closeIcon: false,
                confirmFn: function (e) {
                    var dst_ip = $("#to_host").val()
                    $.ajax({
                        url: '{{ SITE_URL }}clone_host_property/',
                        method: 'post',
                        data: JSON.stringify({
                            "bk_biz_id": bk_biz_id,
                            "bk_org_ip": src_ip,
                            "bk_dst_ip": dst_ip
                        }),
                        success: function (json) {
                            if (!json.result) {
                                var errorMessage = new bkMessage({
                                    message: "克隆主机失败：" + json.message,
                                    theme: 'error'
                                });
                            } else {
                                var successMessage = new bkMessage({
                                    message: '克隆主机' + src_ip + "的属性至" + dst_ip + "成功",
                                    theme: 'success'
                                });
                                businessInfo.ajax.reload()
                            }
                        }
                    });
                }
            });
            dialog.show()
        }

        // 转移主机模块
        function transfer_host_module(host_id) {
            var options = ""
            // 获取模块列表数据
            biz_modules.forEach(function (item) {
                // 点击转移按钮，发送数据到转移接口
                options += '<option value="' + item.bk_module_id + '">' + item.bk_module_name + '</option>'
            })
            var dialog = new bkDialog({
                type: 'dialog',
                width: 400,
                padding: 20,
                content: '<label >转移主机至模块:</label><select class="bk-form-select" style="width: 100%;" id="to_biz_module">' + options + "</select>",
                hasHeader: false,
                closeIcon: false,
                confirmFn: function (e) {
                    var module_id = parseInt($("#to_biz_module").val());
                    $.ajax({
                        url: "{{ SITE_URL }}transfer_host_module/",
                        method: 'POST',
                        data: JSON.stringify({
                            "bk_biz_id": bk_biz_id,
                            "bk_host_id": host_id,
                            "bk_module_id": [module_id],
                            "is_increment": 0
                        }),
                        dataType: 'json',
                        success: function (json) {
                            if (!json.result) {
                                var errorMessage = new bkMessage({
                                    message: "转移模块失败：" + json.message,
                                    theme: 'error'
                                });

                            } else {
                                debugger
                                var successMessage = new bkMessage({
                                    message: '转移主机至模块[' + module_id + "]成功",
                                    theme: 'success'
                                });
                                businessInfo.ajax.reload()
                            }
                        }
                    });
                }
            });
            dialog.show()

        }

        // 业务拓扑树
        function search_biz_inst_topo() {
            biz_modules = []
            $.ajax({
                url: "{{ SITE_URL }}search_biz_inst_topo/",
                method: 'post',
                dataType: 'json',
                data: JSON.stringify({
                    "bk_biz_id": bk_biz_id,
                }),
                success: function (json) {
                    var bk_ul_tops = '<li class="folder open" style="background: #fff"><a href="javascript:;"><i class="bk-icon icon-apps"></i> 业-'
                        + json.bk_inst_name + '</a><a href="#setOperator" data-toggle="modal" data-target="#setOperator"></a>';
                    var sub_str1 = "";
                    module_nums = 0;
                    if (json.child.length > 0) {
                        sub_str1 += '<ul class="tree-secondary">';
                        var sub_str2 = "";
                        json.child.forEach(function (set) {
                            sub_str2 += '<li class="folder set" set_id="' + set.bk_inst_id + '"><a href="javascript:;" ><i class="bk-icon icon-panels"></i> 集-' + set.bk_inst_name + '</a>' +
                                '<a href="#moduleOperator" data-toggle="modal" data-target="#moduleOperator"></a>';

                            if (set.child.length > 0) {
                                module_nums += set.child.length;
                                sub_str2 += '<ul>';
                                var sub_str3 = "";
                                set.child.forEach(function (module) {
                                    sub_str3 += '<li class="file module" module_id="' + module.bk_inst_id + '"><a href="javascript:;" ><i class="tree-icon"></i>模-' + module.bk_inst_name + '</a>' + '</li>';
                                    biz_modules.push({
                                        "bk_module_id": module.bk_inst_id,
                                        "bk_module_name": set.bk_inst_name + "-" + module.bk_inst_name

                                    })
                                });
                                sub_str2 += sub_str3 + '</ul>';
                            }

                            sub_str2 += '</li>';
                        });
                        sub_str1 += sub_str2 + "</ul>";
                    }
                    document.getElementById("bk-ul-tops").innerHTML = bk_ul_tops + sub_str1 + '</li>';
                }
            });
        }

        // 获取告警列表
        function render_alert_table(page=1) {
            filter = get_alert_filter()

            var page_size = 10;
            $.ajax({
                url: "{{ SITE_URL }}get_alert_monitor/",
                method: "post",
                dataType: "json",
                data: JSON.stringify({
                    "filter": filter,
                    "page": page,
                    "page_size": page_size,
                    "bk_biz_id": parseInt($("#search_biz_inst_topo option:selected").val()),
                }),
                success: function (data) {
                    // 渲染表格
                    var html = ``
                    data.data.results.forEach(function (item) {
                        html += `
                            <tr>
                            <td>` + item.alert_id + `</td>
                            <td>` + item.name + `</td>
                            <td>` + item.severity + `</td>
                            <td>` + item.ip + `</td>
                            <td>` + item.category_display + `</td>
                            <td>` + item.status + `</td>
                            <td>` + item.is_shieled + `</td>
                            <td>` + item.is_ack + `</td>
                            <td>` + item.is_handled + `</td>
                            <td>` + item.ack_operator + `</td>
                            <td>` + item.strategy_name + `</td>
                            <td>` + bizNameMapping[item.bk_biz_id] + `</td>
                            </tr>
                        `;
                    })
                    document.getElementById("alert-data").innerHTML = html;

                    renderAlertPaging(Math.ceil(data.data.total / page_size), page);
                    initAlertFilterSelect();
                }
            });
        }

        // 渲染告警列表
        function renderAlertPaging(pageSize, currentPage) {
            var subPaging = "";
            if(pageSize <= 6){
                for(let i = 0; i < pageSize; i++) {
                    var iscurPage = "";
                    if ((i+1) === currentPage) iscurPage = "cur-page";
                    subPaging += `<li class="page-item ${iscurPage}" value="${i+1}"><a href="javascript:void(0);" class="page-button">${i+1}</a></li>`;
                }
            } else {
                var iscurPage1 = "";
                if (1 === currentPage) iscurPage1 = "cur-page";
                subPaging += `<li class="page-item ${iscurPage1}" value="1"><a href="javascript:void(0);" class="page-button">1</a></li>`;


                if (currentPage < 5) {
                    for(let j = 2; j < 6; j++) {
                        var iscurPage2 = "";
                        if (j === currentPage) iscurPage2 = "cur-page";
                        subPaging += `<li class="page-item ${iscurPage2}" value="${j}"><a href="javascript:void(0);" class="page-button">${j}</a></li>`;
                    }
                    subPaging += `<li class="page-item" value="-3"><a href="javascript:void(0);" class="page-button">···</a></li>`;
                } else if (currentPage >= 5 && (pageSize - 5) < currentPage) {
                    subPaging += `<li class="page-item" value="-2"><a href="javascript:void(0);" class="page-button">···</a></li>`;

                    for(let j = pageSize-5; j < pageSize; j++) {
                        var iscurPage2 = "";
                        if (j === currentPage) iscurPage2 = "cur-page";
                        subPaging += `<li class="page-item ${iscurPage2}" value="${j}"><a href="javascript:void(0);" class="page-button">${j}</a></li>`;
                    }
                } else {
                    subPaging += `<li class="page-item" value="-2"><a href="javascript:void(0);" class="page-button">···</a></li>`;

                    for(let j = currentPage - 2; j < currentPage + 3; j++) {
                        if (j !== pageSize) {
                            var iscurPage2 = "";
                            if (j === currentPage) iscurPage2 = "cur-page";
                            subPaging += `<li class="page-item ${iscurPage2}" value="${j}"><a href="javascript:void(0);" class="page-button">${j}</a></li>`;
                        }
                    }

                    subPaging += `<li class="page-item" value="-3"><a href="javascript:void(0);" class="page-button">···</a></li>`;
                }

                var iscurPage3 = "";
                if (pageSize === currentPage) iscurPage3 = "cur-page";
                subPaging += `<li class="page-item ${iscurPage3}" value="${pageSize}"><a href="javascript:void(0);" class="page-button">${pageSize}</a></li>`;
            }

            var isDisabledLiLeft = "";
            var isDisabledLiRight = "";
            if(parseInt(currentPage) === 1) isDisabledLiLeft = "disabled";
            if(pageSize === currentPage) isDisabledLiRight = "disabled";

            var pagingHTML = `<li class="page-item ${isDisabledLiLeft}" value="0">
                <a href="javascript:void(0);" class="page-button">
                    <i class="bk-icon icon-angle-left"></i>
                </a>
            </li>
            ${subPaging}
            <li class="page-item ${isDisabledLiRight}" value="-1">
                <a href="javascript:void(0);" class="page-button">
                    <i class="bk-icon icon-angle-right"></i>
                </a>
            </li>`;
            document.getElementById("tablePaging").innerHTML = pagingHTML;

            // 分页告警数据
            $(".page-item").click(function () {
                var page = $(this).attr('value');
                $(".page-item").removeClass("cur-page");
                $(this).attr("class", "page-item cur-page");
                if (!page && currentPage === 1)
                    page = 1;
                else if (!page && currentPage > 1)
                    page = currentPage - 1;
                else if (page===-1 && currentPage !== pageSize)
                    page = currentPage + 1;
                else if (page===-1 && currentPage === pageSize)
                    page = currentPage;
                else if (page===-2)
                    page = currentPage - 5;
                else if (page===-3)
                    page = currentPage + 5;
                render_alert_table(page);
            });
        }

        // 初始化告警列表筛选
        function initAlertFilterSelect() {
            var headTitle = "";
            var tableTh = $("#warning-list").find("thead").find("th");
            for (let i = 0; i < tableTh.length; i++) {
                var inputHTML = "";
                if ("false" === localStorage.getItem("warning-check-list:" + i)) {
                    inputHTML = `<input type="checkbox"  value="${i}">`;
                    $(`#warning-list th:nth-child(${i + 1})`).hide();
                    $(`#warning-list td:nth-child(${i + 1})`).hide();
                } else {
                    inputHTML = `<input type="checkbox"  checked="checked" value="${i}">`;
                }
                headTitle += `<li><a href="javascript:;"><label class="warning-list-label">${inputHTML} ${tableTh[i].innerText}</label></a></li>`;
            }
            $("#check-list").html(headTitle);

            $(".warning-list-label input").on('click', function () {
                var index = parseInt($(this).attr('value'));
                var isChecked = $(this).prop('checked');
                var thChild = `#warning-list th:nth-child(${index + 1})`;
                var tdChild = `#warning-list td:nth-child(${index + 1})`;
                localStorage.setItem("warning-check-list:" + index, `${isChecked}`);
                if (isChecked) {
                    $(thChild).show();
                    $(tdChild).show();
                } else {
                    $(thChild).hide();
                    $(tdChild).hide();
                }
            });
        }

        // 点击告警列表筛选按钮
        $("#search-button").click(function () {
            if (tabIndex === 2) {
                render_alert_table();
            } else if (tabIndex === 3) {
                render_alert_chart();
            }
        })

        // 获取告警过滤条件
        function get_alert_filter() {
            var status = $("#alert-status option:selected").val()
            var is_shielded = $("#alert-shielded option:selected").val()
            var severity = $("#alert-level option:selected").val()
            var ip = $("#alert-ip").val()
            // 处理过滤条件
            var filter = {}
            if (status.length > 0) {
                filter["status"] = status
            }
            if (is_shielded.length > 0) {
                filter["is_shielded"] = is_shielded === "true"
            }
            if (severity.length > 0) {
                filter["severity"] = severity
            }
            if (ip.length > 0) {
                filter["ip"] = ip
            }
            return filter
        }

        // 渲染告警图标
        function render_alert_chart() {
            // 获取告警数据
            $.ajax({
                url: "{{ SITE_URL }}get_alert_monitor_group_data/",
                method: "post",
                dataType: "json",
                data: JSON.stringify({
                    "bk_biz_id": bk_biz_id,
                }),
                async: false,
                success: function (data) {
                    let chart_data = data.data
                    let alert_ip_chart = echarts.init(document.getElementById("alert_ip"))
                    alert_ip_chart.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: '告警IP <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            type: 'scroll',
                            orient: 'vertical',
                            right: 30,
                            top: 100,
                            length: 10
                        },
                        series: [
                            {
                                type: 'pie',
                                radius: ['40%', '55%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 0,
                                    borderColor: '#fff',
                                    borderWidth: 1
                                },
                                label: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: 20
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: chart_data["ip"]
                            }
                        ]
                    })
                    let alert_name_chart = echarts.init(document.getElementById("alert_name"))
                    alert_name_chart.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: '告警名称 <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            type: 'scroll',
                            orient: 'vertical',
                            right: 10,
                            top: 100,
                            formatter: function (name) {
                                if (name.length > 10) {
                                    return name.substring(0, 10) + "..."
                                } else {
                                    return name
                                }
                            }
                        },
                        series: [
                            {
                                type: 'pie',
                                radius: ['40%', '55%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 0,
                                    borderColor: '#fff',
                                    borderWidth: 1
                                },
                                label: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: 20
                                    }
                                },
                                labelLine: {
                                    show: true
                                },
                                data: chart_data["name"]
                            }
                        ]
                    });
                    let alert_level_chart = echarts.init(document.getElementById("alert_level"))
                    alert_level_chart.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: '告警等级 <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            type: 'scroll',
                            orient: 'vertical',
                            right: 50,
                            top: 100,
                        },
                        series: [
                            {
                                type: 'pie',
                                radius: ['40%', '55%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 0,
                                    borderColor: '#fff',
                                    borderWidth: 1
                                },
                                label: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: 20,
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: chart_data["severity"]
                            }
                        ]
                    });
                    var alert_status_chart = echarts.init(document.getElementById("alert_status"))
                    alert_status_chart.setOption({
                        tooltip: {
                            trigger: 'item',
                            formatter: '告警状态 <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            type: 'scroll',
                            orient: 'vertical',
                            right: 50,
                            top: 100,
                            bottom: 20
                        },
                        series: [
                            {
                                type: 'pie',
                                radius: ['40%', '55%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 0,
                                    borderColor: '#fff',
                                    borderWidth: 1
                                },
                                label: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: 20,
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: chart_data["status"]
                            }
                        ]
                    });
                }
            })
        }

        function translation_machine(origin_ip, index, host_id) {

            // 获取SOPS模板列表
            var sops_template_list = get_sops_templates()
            // 获取选择的模板
            var templates = []
            sops_template_list.data.forEach(function (item) {
                templates.push(item.id + " " + item.name)
            })

            var target_ips = get_free_host_list(origin_ip)

            // 获取完成基础变量后，渲染模态框
            render_modal_info(templates, origin_ip, target_ips)
            // 模拟点击模态框弹出按钮，触发显示模态框
            $("#modal-button").click()

            var template_id = ``
            var target_ip = ``
            // 点击提交按钮，获取参数内容，创建任务
            $("#submit-button").click(function () {
                // 禁用故障机切换按钮 style=pointer-events:none
                $(`#hosts tbody`).find("tr:eq(" + index + ") td:eq(7) a:eq(3)").attr("style", "pointer-events:none; color: rgb(185 181 175);")
                template_id = $('#template-id option:selected').val()
                target_ip = $('#target-ip option:selected').val()

                // 使用选择的流程模板创建任务并执行日志
                create_and_execute_task(origin_ip, target_ip, template_id, host_id)
                // 关闭模态框
                $(".close").click()
                // 弹出消息
                $("#alert-message").attr("style", "display:block; float:right;")
                setInterval(function () {
                    // 关闭消息
                    $("#alert-message").attr("style", "display:none")
                }, 3000)
            })
        }

        // 渲染模态框内容
        function render_modal_info(templates, origin_ip, target_ips) {
            // 模态框需要渲染的内容 流程模板选择器 全局参数origin_ip target_ip渲染
            // 渲染流程模板内容
            var select_template_html = `
                <p>请选择流程模板ID:
                <select name="" id="template-id" style="margin-left:30px">
            `
            templates.forEach(function (item) {
                var id, name
                id = item.split(" ")[0]
                name = item.split(" ")[1]
                select_template_html += `<option value="` + id + `">` + name + `</option>`
            })
            select_template_html += "</select></p>"
            document.getElementById("select-template").innerHTML = select_template_html

            // 渲染故障机IP
            document.getElementById("render-origin-ip").innerHTML = origin_ip

            // 渲染备份机内容
            var select_target_html = `
                <p>请选择备份机:
                <select name="" id="target-ip" style="margin-left:59px">
            `
            target_ips.forEach(function (item) {
                select_target_html += `<option value="` + item + `">` + item + `</option>`
            })
            select_target_html += "</select></p>"
            document.getElementById("select-target-ip").innerHTML = select_target_html
        }

        // 获取模板列表
        function get_sops_templates() {
            var result = ``
            $.ajax({
                url: "{{ SITE_URL }}sops_get_template_list/?bk_biz_id=" + parseInt($("#search_biz_inst_topo option:selected").val()),
                method: "get",
                // 同步执行
                async: false,
                success: function (data) {
                    result = data
                }
            })
            return result
        }

        // 使用选择的流程模板ID创建任务
        function create_and_execute_task(origin_ip, target_ip, template_id, host_id) {
            var now = new Date()
            var date = `` + now.getUTCFullYear() + `` + (now.getMonth() + 1) + `` + now.getDate() + `` + now.getHours() + `` + now.getMinutes() + `` + now.getSeconds() + ``
            $.ajax({
                url: "{{ SITE_URL }}sops_create_and_execute_task/",
                method: "post",
                dataType: "json",
                data: JSON.stringify({
                    "name": "new_task_" + date,
                    "bk_biz_id": parseInt($("#search_biz_inst_topo option:selected").val()),
                    "template_id": parseInt(template_id),
                    "host_id": parseInt(host_id),
                    "constants": {
                        "${origin_ip}": origin_ip,
                        "${target_ip}": target_ip
                    }
                }),
                // 同步执行
                async: false,
                success: function (data) {
                }
            })
        }

        // 查询任务状态
        function get_sops_task_status(host_id) {
            var status = ""
            $.ajax({
                url: "{{ SITE_URL }}sops_status_task/?host_id=" + host_id,
                method: "get",
                // 同步执行
                async: false,
                success: function (data) {
                    status = data.data.task_status
                }
            })
            return status
        }

        // 查询空闲机模块中的所有机器
        function get_free_host_list(origin_ip) {
            var free_ip_list = []
            var bk_biz_id = parseInt($("#search_biz_inst_topo option:selected").val())
            $.ajax({
                url: '{{ SITE_URL }}list_free_hosts/?bk_biz_id=' + bk_biz_id,
                method: "get",
                async: false,
                success: function (data) {
                    data.data.info.forEach(function (item) {
                        if (item.bk_host_innerip != origin_ip) {
                            free_ip_list.push(item.bk_host_innerip)
                        }
                    })
                }

            })
            return free_ip_list
        }
    </script>
{% endblock %}